package com.css.dzj.dzjjcss.modules.venue.service.impl;

import com.css.dzj.dzjjcss.common.util.Constant;
import com.css.dzj.dzjjcss.common.util.ServiceUtil;
import com.css.dzj.dzjjcss.common.util.excel.ExcelData;
import com.css.dzj.dzjjcss.common.util.excel.ExportExcelUtils;
import com.css.dzj.dzjjcss.modules.todo.service.TodoService;
import com.css.dzj.dzjjcss.modules.venue.AdmExcelVerifyHandler;
import com.css.dzj.dzjjcss.modules.venue.entity.VenueEntity;
import com.css.dzj.dzjjcss.modules.venue.entity.QVenueEntity;
import com.css.dzj.dzjjcss.modules.venue.mapper.VenueMapper;
import com.css.dzj.dzjjcss.modules.venue.service.VenueService;
import com.css.dzj.dzjjcss.modules.venue.vo.VueExcelVo;
import com.css.dzj.dzjjcss.common.util.SnowflakeId;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 场地场所实现层
 */
@Service
public class VenueServiceImpl implements VenueService {

    @Autowired
    private VenueMapper venueMapper;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private HttpServletRequest request;

    //代办接口
    @Autowired
    private TodoService todoService;
    @Autowired
    private AdmExcelVerifyHandler admExcelVerifyHandler;


    /**
     * 新增公示通报信息
     */
    @Override
    @Transactional
    public void add(VenueEntity pEntity) {

        try {
            pEntity.setCreateUser(ServiceUtil.getLoginName(request));
            //pEntity.setId(SnowflakeId.getId());
            pEntity.setDelFlag(Constant.NO_DELETE);
            pEntity.setCreateTime(new Date());
            pEntity.setStatus("1");
            venueMapper.save(pEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 暂存公示通报信息
     */
    @Override
    @Transactional
    public void addOnly(VenueEntity pEntity) {

        try {
            pEntity.setCreateUser(ServiceUtil.getLoginName(request));
            //pEntity.setId(SnowflakeId.getId());
            pEntity.setDelFlag(Constant.NO_DELETE);
            pEntity.setCreateTime(new Date());
            pEntity.setStatus("0");
            venueMapper.save(pEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改公示通报信息
     */
    @Override
    @Transactional
    public void update(VenueEntity pEntity) {

    }

    /**
     * 通过id查询公示通报信息
     */
    @Override
    public VenueEntity findById(String placeId) {
        if (StringUtils.isEmpty(placeId)) {
            throw new RuntimeException("传递参数为空");
        }
        QVenueEntity qEntity = QVenueEntity.venueEntity;
        return jpaQueryFactory
                .selectFrom(qEntity)
                .where(qEntity.placeId.eq(placeId),
                        qEntity.delFlag.eq(Constant.NO_DELETE)
                )
                .fetchOne();
    }

    /**
     * 分页查询公示通报信息
     */
    @Override
    public QueryResults<VenueEntity> queryPage(Pageable pageable) {

        QVenueEntity qEntity = QVenueEntity.venueEntity;
        Predicate predicate = qEntity.isNotNull().or(qEntity.isNull());
        predicate = ExpressionUtils.and(predicate, qEntity.delFlag.eq(Constant.NO_DELETE));
        QueryResults<VenueEntity> publicResults = jpaQueryFactory.selectFrom(qEntity)
                .where(predicate)
                .orderBy(qEntity.createTime.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
        return publicResults;
    }

    /**
     * 删除公示通报信息
     */
    @Override
    @Transactional
    public Boolean delete(String placeId) {

        if (StringUtils.isEmpty(placeId)) {
            throw new RuntimeException("传递参数为空");
        }
        try {
            QVenueEntity qEntity = QVenueEntity.venueEntity;
            jpaQueryFactory
                    .update(qEntity)
                    .set(qEntity.delFlag, Constant.DELETE)
                    .where(
                            qEntity.placeId.eq(placeId),
                            qEntity.delFlag.eq(Constant.NO_DELETE)
                    )
                    .execute();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 向交换系统提供接口
     */
    @Override
    public List queryAllJcss() {
        QVenueEntity q = QVenueEntity.venueEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));
        List<VenueEntity> list = jpaQueryFactory.selectFrom(q)
                .where(predicate)
                .orderBy(q.createTime.desc())
                .fetch();
        return list;
    }
    @Override
    public QueryResults<VenueEntity> getGstbList(String placeName,String areaNumber,String responsibleDept,String chargePerson,String placePurpose,String status, Pageable pageable){
        QVenueEntity q = QVenueEntity.venueEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        //String orgName = ServiceUtil.getOrgName(request);
        predicate = ("".equals(placeName) || placeName == null) ? predicate : ExpressionUtils.and(predicate, q.placeName.like("%"+placeName+"%"));
        predicate = ("".equals(areaNumber) || areaNumber == null) ? predicate : ExpressionUtils.and(predicate, q.areaNumber.like("%"+areaNumber+"%"));
        predicate = ("".equals(responsibleDept) || responsibleDept == null) ? predicate : ExpressionUtils.and(predicate, q.responsibleDept.like("%"+responsibleDept+"%"));
        predicate = ("".equals(chargePerson) || chargePerson == null) ? predicate : ExpressionUtils.and(predicate, q.chargePerson.like("%"+chargePerson+"%"));
        predicate = ("".equals(placePurpose) || placePurpose == null) ? predicate : ExpressionUtils.and(predicate, q.placePurpose.eq(placePurpose));
        predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, q.status.eq(status));
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE)) ;
        return  jpaQueryFactory
                .selectFrom(q)
                .where(
                        predicate
                )
                .orderBy(q.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();

    }
    @Override
    public List<VenueEntity> queryByIds(String ids) {
        if (com.alibaba.druid.util.StringUtils.isEmpty(ids)) {
            throw new RuntimeException("ids为空!");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        List<VenueEntity> venueEntity = venueMapper.findAllById(idList);
        return venueEntity;
    }

    @Override
    public void exportAdmPenaltyToExcel(HttpServletResponse response, List<VenueEntity> venueEntity) {
        if (venueEntity == null || venueEntity.size() < 0) {
            throw new RuntimeException("场地场所信息为空");
        }
        // 创建导出实体
        ExcelData data = new ExcelData();
        data.setName("场地场所信息表");
        /**
         * 设置Excel标题
         */
        ArrayList<String> titles = new ArrayList<>();
        titles.add("序号");
        titles.add("场地场所名称");
        titles.add("所在地区");
        titles.add("所在地区行政区划代码");
        titles.add("责任单位");
        titles.add("责任单位统一社会信用代码");
        titles.add("责任人");
        titles.add("责任人证件类型");
        titles.add("责任人证件编码");
        titles.add("联系电话");
        titles.add("场地场所用途");
        titles.add("场地规模");
        titles.add("投入使用开始时间");
        titles.add("使用寿命");
        data.setTitles(titles);
        /**
         * 处理行数据
         */
        ArrayList<List<Object>> rows = new ArrayList<>();
        for (int i = 0; i < venueEntity.size(); i++) {
            ArrayList<Object> row = new ArrayList<>();
            row.add(String.valueOf(i + 1));
            row.add(venueEntity.get(i).getPlaceName());
            row.add(venueEntity.get(i).getArea());
            row.add(venueEntity.get(i).getAreaNumber());
            row.add(venueEntity.get(i).getResponsibleDept());
            row.add(venueEntity.get(i).getEnterpriseCreditCode());
            row.add(venueEntity.get(i).getChargePerson());
            row.add(venueEntity.get(i).getCertificateType());
            row.add(venueEntity.get(i).getCertificateNumber());
            row.add(venueEntity.get(i).getContactTel());
            row.add(venueEntity.get(i).getPlacePurpose());
            row.add(venueEntity.get(i).getPlaceScale());
            SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
            String formaTime = spf.format(venueEntity.get(i).getStartDate());
            row.add(formaTime);
            row.add(venueEntity.get(i).getDeviceLifetime());
            rows.add(row);
        }
        data.setRows(rows);
        try {
            // 导出
            ExportExcelUtils.exportExcel(response, "场地场所信息表.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<VenueEntity> queryByParams(String placeName,String areaNumber,String responsibleDept,String chargePerson,String placePurpose,String status) {
        QVenueEntity q = QVenueEntity.venueEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        //String orgName = ServiceUtil.getOrgName(request);
        predicate = ("".equals(placeName) || placeName == null) ? predicate : ExpressionUtils.and(predicate, q.placeName.like("%"+placeName+"%"));
        predicate = ("".equals(areaNumber) || areaNumber == null) ? predicate : ExpressionUtils.and(predicate, q.areaNumber.like("%"+areaNumber+"%"));
        predicate = ("".equals(responsibleDept) || responsibleDept == null) ? predicate : ExpressionUtils.and(predicate, q.responsibleDept.like("%"+responsibleDept+"%"));
        predicate = ("".equals(chargePerson) || chargePerson == null) ? predicate : ExpressionUtils.and(predicate, q.chargePerson.like("%"+chargePerson+"%"));
        predicate = ("".equals(placePurpose) || placePurpose == null) ? predicate : ExpressionUtils.and(predicate, q.placePurpose.eq(placePurpose));
        predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, q.status.eq(status));
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE)) ;
        return  jpaQueryFactory
                .selectFrom(q)
                .where(
                        predicate
                )
                .orderBy(q.createTime.desc())
                .fetch();
    }


    @Override
    @Transactional
    public String uploadFile(MultipartFile file, HttpServletResponse response) {
        try {
            StringBuilder returnMsg = new StringBuilder();
            String[] head = new String[]{"场地场所名称","所在地区","所在地区行政区划代码","责任单位","责任单位统一社会信用代码",
                    "责任人","责任人证件类型","责任人证件编码","联系电话","场地场所用途",
                    "场地规模","投入使用开始时间(YYYY-MM-DD)","使用寿命(年)"};
            ImportParams params = new ImportParams();
            params.setHeadRows(1);
            //*params.setNeedVerify(true);*//*
            params.setKeyIndex(0);
            params.setNeedVerify(true);
            params.setImportFields(head);
            params.setVerifyHandler(admExcelVerifyHandler);
            ExcelImportResult<VueExcelVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), VueExcelVo.class, params);
            List<VueExcelVo> list = result.getList();
            //校验数据（暂时用不到）
            /*if( null !=list && list.size()>0){
                checkList(list);
            }*/
            Iterator it = list.iterator();
            VueExcelVo vueExcelVo;

            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");

            list.forEach((e) -> {
                VenueEntity entity = new VenueEntity();
                entity.setPlaceId(SnowflakeId.getId());
                BeanUtils.copyProperties(e, entity);
                this.addOnly(entity);
            });

            if (result.isVerifyFail()) {
                it = result.getFailList().iterator();

                while(it.hasNext()) {
                    vueExcelVo = (VueExcelVo)it.next();
                    String msg = "";
                    returnMsg.append("第" + vueExcelVo.getRowNum() + "行" + vueExcelVo.getErrorMsg() + "<br/>");
                    returnMsg.append(msg);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

}
